<template>
  <view style="height: 100vh;">
    <layout layoutTitle="智能助手">
      <view class="chat-container">
        <scrollView :messageList="messageList" @send="sendMessage" v-model:modelValue="inputMessage"></scrollView>
      </view>
    </layout>
  </view>
</template>

<script setup>
import { ref } from 'vue'

// 消息列表
const messageList = ref([
  {
    text: '欢迎访问智能双碳助手',
    title: 'ai助手',
    isUser: false,
    ava: '/static/images/img/222.jpg'
  }
])
// 输入框内容
const inputMessage = ref('')

// 发送消息
async function sendMessage(message) {
  if (message.trim() === '') return

  // 添加用户消息
  messageList.value.push({
    text: message,
    title: '用户',
    isUser: true,
    ava: '/static/images/login/icon.png'
  })

  // 添加 AI 响应占位
  const aiResponse = ref({
    text: '',
    title: 'ai助手',
    isUser: false,
    ava: '/static/images/img/222.jpg'
  })
  messageList.value.push(aiResponse.value)

  // 调用接口
  try {
    const response = await fetch(`http://localhost:9091/AiChat/${encodeURIComponent(message)}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    // 流式读取数据
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let aiText = ''
    while (true) {
      const { value, done } = await reader.read()
      if (done) break
      aiText += decoder.decode(value, { stream: true })
      aiResponse.value.text = aiText
    }
  } catch (error) {
    console.error("AI聊天请求失败:", error)
    aiResponse.value.text = "抱歉，我暂时无法连接到服务器，请稍后再试。"
  }
}
</script>

<style>
/* 父组件样式 */
.chat-container {
  height: 100%;
  width: 100%;
  background: linear-gradient(165deg, #f6fbf8, #e8f5f0);
  position: relative;
}
</style>